<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title> 文字打印效果 </title>
</head>
<body>
	
	<div id="text"></div>

<script>
	const Ptext = (arr, id, time) => {
		let p = "";
		let pos = 1;
		let row = 0; // 记录行数
		let index = 0; // 记录数组索引
		let timer = null;
		let len = arr.length; // 记录数组长度
		let strlen = arr[0].length; // 获取数组第一个字符串长度
		let oText = document.getElementById(id);


		function printText(){
			if(row < index){
				p = p + arr[row++] + "<br/>";
			}

			oText.innerHTML = p + arr[index].substring(0, pos);

			if(strlen == pos){
				pos = 0;
				index ++; // 下一个字符串的位置
				if(index < len){
					strlen = arr[index].length;
					timer = setTimeout(printText, time);
				} else {
					clearTimeout(timer);
				}	
			} else {
				pos++;
				timer = setTimeout(printText, time);
			}
		}
		printText();
	}

	Ptext(["文字打印效果", "adasdas", "nihaoasdsadsad"], "text", 100);
</script>
</body>
</html>
